package com.wyp168.leetcode;

public class CountAndSay {

    public static void main(String[] args) {
        System.out.println(countAndSay(4));
    }

    public static String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        String str = countAndSay(n - 1);
        //转换为字符数组，方便后期操作
        char[] strc = str.toCharArray();
        //第一个字符
        char c1 = strc[0];
        //定义一个StringBuilder，封装统计结果并返回
        StringBuilder sb = new StringBuilder();
        int count = 0;
        for (int i = 0;i < str.length(); i++) {
            if(strc[i] == c1) {
                count ++;
            } else {
                sb.append(count);
                sb.append(c1);
                c1 = strc[i];
                count = 1;
            }
            if (i == strc.length - 1) {
                sb.append(count);
                sb.append(c1);
            }
        }
        return sb.toString();
    }
}
